
import pygame
import time
import sys
import configparser
from enum import Enum
from pygame.locals import *
pygame.init()
pygame.joystick.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()
interval = 0.5


class GameButton(Enum):
    
    """
    定义一个枚举类型，表示游戏手柄的按钮

    Logit F710 Direct：X0 A1 B2 Y3 LB4 RB5 LT6 RT7 BACK8 START9
    
    GameSir G4S：X3 A0 B1 Y4 LB6 RB7 LT8 RT9
    """
    X = 3
    A = 0
    B = 1
    Y = 4
    LB = 6  # Left Bumper
    RB = 7  # Right Bumper
    LT = 8  # Left Trigger
    RT = 9  # Right Trigger
    G = 10
    S = 11
    Start = 15

def load_config(ini_path):
    """
    加载配置文件并返回配置对象。

    参数:
    ini_path (str): 配置文件的路径。

    返回:
    configparser.ConfigParser: 配置对象。
    """           
    config = configparser.ConfigParser()
    config.read(ini_path)
    return config

def map_button_to_action(button1, button2, ini_path='config.ini'):
    """
    根据手柄按钮组合映射到相应的动作。

    参数:
    button1 (int): 第一个按钮的索引。
    button2 (int): 第二个按钮的索引。
    ini_path (str): 配置文件的路径，默认为 'config.ini'。

    返回:
    str: 对应的动作，如果未找到则返回 None。
    """
    button1, button2 = sortButton(button1, button2)
    
    # 加载配置
    config = load_config(ini_path)

    # 获取按钮名称
    button1_name = GameButton(button1).name
    
    action_key = ""
    if button2 is None:
        # 查找对应的组合动作
        action_key = f"{button1_name}"
    else:
        button2_name = GameButton(button2).name
        action_key = f"{button1_name}_{button2_name}"

        # 如果没有这个组合键，尝试反转组合键 (比如 X_A 和 A_X 都可以)
        if action_key not in config['gamepad']:
            action_key = f"{button2_name}_{button1_name}"

    print(f"Pressed {action_key}")
    # 获取动作
    action = config['gamepad'].get(action_key, None)
    # print(f"Assigned action: {action}")
    return action


def sortButton(button1, button2):
    """
    对两个按钮索引进行排序，确保 button1 小于等于 button2。

    参数:
    button1 (int): 第一个按钮的索引。
    button2 (int): 第二个按钮的索引。

    返回:
    tuple: 排序后的按钮索引元组。
    """
    if(button1 is not None):
        if(button2 is None):
            return button1,button2
        elif(button1>button2):
            return button2,button1
        elif(button1<button2):
            return button1,button2
        else:
            print("Error: sortButton")
            return button1, button2
    else:
        return button2, button1

def get_gamepad_action():
    """
    获取游戏手柄对应的动作。

    监听手柄事件，并根据按钮组合返回相应的动作。

    返回:
    str: 手柄动作的字符串表示，如果未检测到动作则不返回。
    """
    while True:
        button1 = None
        button2 = None
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.JOYBUTTONDOWN:
                button1 = event.button
                # print(f'Button {button1} pressed')
                t1 = time.time()
                flag=True
                while flag:
                    for event in pygame.event.get():
                        if event.type == pygame.JOYBUTTONDOWN:
                            button2 = event.button
                            # print(f'Button {button2} pressed')
                            if(button1 == button2):
                                button2 = None
                                flag = False
                                break
                            else:
                                # print(f'Button{button1},{button2} pressed')
                                pass
                                
                    if(time.time()-t1>interval):
                        flag=False 
                        break    
            elif event.type == pygame.JOYHATMOTION:
                print(f'Hat {event.hat} moved')
            
        if(button1 is not None or button2 is not None):
            # print(f'Button {button1},{button2} pressed')
            action = map_button_to_action(button1, button2)
            return action
        
        pygame.time.wait(10)
        # joystick_axes = [joystick.get_axis(i) for i in range(joystick.get_numaxes())]
        # joystick_buttons = [joystick.get_button(i) for i in range(joystick.get_numbuttons())]
        # print(f'Axes: {joystick_axes} Buttons: {joystick_buttons}')

def get_gamepad_action2():
    """
    获取游戏手柄对应的动作。

    监听手柄事件，在 0.5 秒内检测是否有两个按钮按下，
    如果没有第二个按钮按下，返回第一个按钮对应的动作。

    返回:
    str: 手柄动作的字符串表示，如果未检测到动作则不返回。
    """
    button1 = None
    button2 = None
    start_time = time.time()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == pygame.JOYBUTTONDOWN:
                if button1 is None:
                    button1 = event.button
                    start_time = time.time()  # 重新开始计时
                elif button2 is None and event.button != button1:
                    button2 = event.button

            elif event.type == pygame.JOYHATMOTION:
                print(f'Hat {event.hat} moved')

        # 如果在 0.5 秒内，两个按钮都被按下，返回组合动作
        if button1 is not None and button2 is not None:
            action = map_button_to_action(button1, button2)
            return action
        
        # 超过 0.5 秒没有第二个按钮按下，返回第一个按钮的动作
        if time.time() - start_time > 0.5:
            if button1 is not None:
                button2 = None
                action = map_button_to_action(button1, button2)  # button2 为 None
                return action
        
        pygame.time.wait(10)  # 控制CPU占用，避免空转

if __name__ == '__main__':
    print(get_gamepad_action2())